package com.example.grpcclient.service;

import com.example.grpc.proto.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import net.devh.boot.grpc.client.inject.GrpcClient;
import com.example.grpcclient.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserClientService {

    private static final Logger logger = LoggerFactory.getLogger(UserClientService.class);

    @GrpcClient("user-service")
    private UserServiceGrpc.UserServiceBlockingStub userServiceStub;
    
    @Value("${grpc.client.user-service.address:static://localhost:9090}")
    private String grpcServerAddress;
    
    private boolean useManualChannel = false;
    
    @PostConstruct
    public void init() {
        // 如果注入的 stub 为 null，则手动创建一个
        if (userServiceStub == null) {
            logger.info("通过 @GrpcClient 注入的 stub 为 null，使用手动方式创建 gRPC 通道");
            useManualChannel = true;
            String address = grpcServerAddress.replace("static://", "");
            String[] parts = address.split(":");
            String host = parts[0];
            int port = parts.length > 1 ? Integer.parseInt(parts[1]) : 9090;
            
            ManagedChannel channel = ManagedChannelBuilder
                .forAddress(host, port)
                .usePlaintext()
                .enableRetry()
                .maxRetryAttempts(5)
                .build();
                
            userServiceStub = UserServiceGrpc.newBlockingStub(channel);
            logger.info("手动创建 gRPC 通道成功，连接到 {}:{}", host, port);
        } else {
            logger.info("使用 @GrpcClient 注入的 stub");
        }
    }

    /**
     * 获取用户信息
     *
     * @param id 用户ID
     * @return 用户信息
     */
    public UserDto getUser(int id) {
        logger.info("发送获取用户请求，用户ID: {}", id);
        UserRequest request = UserRequest.newBuilder().setId(id).build();
        UserResponse response = userServiceStub.getUser(request);
        logger.info("接收到用户信息: {}", response);
        return convertToDto(response);
    }

    private UserDto convertToDto(UserResponse userResponse) {
        return new UserDto(
                userResponse.getId(),
                userResponse.getName(),
                userResponse.getEmail(),
                userResponse.getAge()
        );
    }

    /**
     * 创建用户
     *
     * @param name  用户名
     * @param age   年龄
     * @param email 邮箱
     * @return 创建的用户信息
     */
    public UserDto createUser(String name, int age, String email) {
        logger.info("发送创建用户请求: name={}, age={}, email={}", name, age, email);
        CreateUserRequest request = CreateUserRequest.newBuilder()
                .setName(name)
                .setAge(age)
                .setEmail(email)
                .build();
        CreateUserResponse response = userServiceStub.createUser(request);
        logger.info("用户创建成功: {}", response);
        return convertToDto(response.getUser());
    }

    /**
     * 获取所有用户
     *
     * @return 用户列表
     */
    public List<UserDto> listUsers() {
        logger.info("发送获取所有用户请求");
        Empty request = Empty.newBuilder().build();
        UserListResponse response = userServiceStub.listUsers(request);
        logger.info("接收到用户列表，共 {} 个用户", response.getUsersCount());
        return response.getUsersList().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
}